import { fetch, patch, cascade } from 'plugins/axios'
import { date, Dialog, QSpinnerGears } from 'quasar'

export function loadData ({state, commit}, payload) {
  let url = '/hosts/' + payload + '/'
  fetch(url, {
  }).then((response) => {
    commit('loadSucess', response)
  }).catch((error) => {
    alert(error.response)
  })
  state.type = this._vm.$data.$$state.listHost.type
  state.re_per = this._vm.$data.$$state.listHost.re_per
  state.status = this._vm.$data.$$state.listHost.status
}

export function save ({state, commit}) {
  Dialog.create({
    title: '修改主机',
    message: '确定修改主机？',
    ok: '提交',
    cancel: '再想想'
  }).then(() => {
    let url = '/hosts/' + state.fields.id + '/'
    state.loading.show({spinner: QSpinnerGears})
    state.fields.terminal_time = date.formatDate(state.fields.terminal_time, 'YYYY-MM-DD')
    patch(url,
      state.fields
    ).then((response) => {
      commit('saveSuccess')
    }).catch((error) => {
      if (error.response.data) {
        commit('saveFail', error.response.data)
      }
    })
  }).catch(() => {
    console.log('stay')
  })
}

export function deleteData ({state}, payload) {
  Dialog.create({
    title: '删除主机',
    message: '确定要删库？',
    ok: '跑路',
    cancel: '再想想'
  }).then(() => {
    state.loading.show({spinner: QSpinnerGears})
    let url = '/hosts/' + state.fields.id + '/'
    cascade(url).then((response) => {
      state.loading.hide()
      this.$router.push('/listhost')
    }).catch((error) => {
      state.loading.hide()
      console.log(error.response.data.detail)
    })
  }).catch(() => {
    console.log('stay')
  })
}
